<template>
  <div class="field-selector">
    <el-button type="text" @click="showDialog = true">
      <el-icon><Setting /></el-icon>
      字段设置
    </el-button>
    
    <el-dialog
      v-model="showDialog"
      width="600px"
      :before-close="handleClose"
      :close-on-click-modal="false"
      class="unified-dialog"
    >
      <!-- 统一头部 -->
      <template #header>
        <div class="dialog-header">
          <div class="header-icon header-icon-primary">
            <el-icon><Setting /></el-icon>
          </div>
          <div class="header-content">
            <h3>字段设置</h3>
            <p>选择和排序要显示的字段</p>
          </div>
        </div>
      </template>
      <div class="field-settings">
        <!-- 字段选择区域 -->
        <div class="field-selection">
          <h4>选择字段</h4>
          <el-checkbox-group v-model="selectedFields" @change="handleFieldChange">
            <div class="field-group">
              <h5>基础信息</h5>
              <el-checkbox
                v-for="field in basicFields"
                :key="field.value"
                :value="field.value"
                :disabled="field.required"
              >
                {{ field.label }}
                <el-tag v-if="field.required" type="info" size="small">必选</el-tag>
              </el-checkbox>
            </div>
            
            <div class="field-group">
              <h5>状态信息</h5>
              <el-checkbox
                v-for="field in statusFields"
                :key="field.value"
                :value="field.value"
              >
                {{ field.label }}
              </el-checkbox>
            </div>
            
            <div class="field-group">
              <h5>时间信息</h5>
              <el-checkbox
                v-for="field in timeFields"
                :key="field.value"
                :value="field.value"
              >
                {{ field.label }}
              </el-checkbox>
            </div>
            
            <div class="field-group">
              <h5>其他信息</h5>
              <el-checkbox
                v-for="field in otherFields"
                :key="field.value"
                :value="field.value"
              >
                {{ field.label }}
              </el-checkbox>
            </div>
          </el-checkbox-group>
        </div>
        
        <!-- 字段排序区域 -->
        <div class="field-sorting">
          <h4>字段排序</h4>
          <div class="sort-list">
            <div
              v-for="(field, index) in sortedFields"
              :key="field.value"
              class="sort-item"
            >
              <div class="field-info">
                <span class="drag-icon">⋮⋮</span>
                <span>{{ field.label }}</span>
                <el-tag v-if="field.required" type="info" size="small">必选</el-tag>
              </div>
              <div class="sort-controls">
                <el-button
                  size="small"
                  :disabled="index === 0"
                  @click="moveUp(index)"
                  circle
                  type="primary"
                  plain
                >
                  ↑
                </el-button>
                <el-button
                  size="small"
                  :disabled="index === sortedFields.length - 1"
                  @click="moveDown(index)"
                  circle
                  type="primary"
                  plain
                >
                  ↓
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleReset">重置默认</el-button>
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick } from 'vue'
import { debounce } from 'lodash-es'
import { componentLogger } from '@/utils/logger'

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  fieldConfig: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const showDialog = ref(false)
const selectedFields = ref([...props.modelValue])
const fieldOrder = ref([...props.modelValue]) // 字段排序顺序

// 字段分组
const basicFields = computed(() => props.fieldConfig.basic || [])
const statusFields = computed(() => props.fieldConfig.status || [])
const timeFields = computed(() => props.fieldConfig.time || [])
const otherFields = computed(() => props.fieldConfig.other || [])

// 所有字段的映射
const allFieldsMap = computed(() => {
  const allFields = [
    ...basicFields.value,
    ...statusFields.value,
    ...timeFields.value,
    ...otherFields.value
  ]
  const map = {}
  allFields.forEach(field => {
    map[field.value] = field
  })
  return map
})

// 已选择字段的排序列表
const sortedFields = computed(() => {
  return fieldOrder.value
    .filter(fieldValue => selectedFields.value.includes(fieldValue))
    .map(fieldValue => allFieldsMap.value[fieldValue])
    .filter(Boolean)
})

// 处理字段变化 - 使用防抖优化性能
const handleFieldChange = debounce((value) => {
  selectedFields.value = value
  
  // 更新排序顺序，移除未选择的字段，添加新选择的字段到末尾
  const newOrder = fieldOrder.value.filter(fieldValue => value.includes(fieldValue))
  const newFields = value.filter(fieldValue => !fieldOrder.value.includes(fieldValue))
  fieldOrder.value = [...newOrder, ...newFields]
}, 100)

// 上移字段
const moveUp = (index) => {
  if (index > 0) {
    const fields = [...fieldOrder.value]
    const selectedFieldValues = fields.filter(fieldValue => selectedFields.value.includes(fieldValue))
    const fieldValue = selectedFieldValues[index]
    const newIndex = index - 1
    
    // 在原始数组中交换位置
    const originalIndex = fields.indexOf(fieldValue)
    const targetFieldValue = selectedFieldValues[newIndex]
    const targetOriginalIndex = fields.indexOf(targetFieldValue)
    
    // 交换位置
    fields[originalIndex] = targetFieldValue
    fields[targetOriginalIndex] = fieldValue
    
    fieldOrder.value = fields
  }
}

// 下移字段
const moveDown = (index) => {
  const selectedFieldValues = fieldOrder.value.filter(fieldValue => selectedFields.value.includes(fieldValue))
  if (index < selectedFieldValues.length - 1) {
    const fields = [...fieldOrder.value]
    const fieldValue = selectedFieldValues[index]
    const newIndex = index + 1
    
    // 在原始数组中交换位置
    const originalIndex = fields.indexOf(fieldValue)
    const targetFieldValue = selectedFieldValues[newIndex]
    const targetOriginalIndex = fields.indexOf(targetFieldValue)
    
    // 交换位置
    fields[originalIndex] = targetFieldValue
    fields[targetOriginalIndex] = fieldValue
    
    fieldOrder.value = fields
  }
}

// 重置为默认字段
const handleReset = () => {
  const defaultFields = []
  
  // 添加必选字段
  basicFields.value.forEach(field => {
    if (field.required) {
      defaultFields.push(field.value)
    }
  })
  
  // 添加默认字段
  const allFields = [
    ...basicFields.value,
    ...statusFields.value,
    ...timeFields.value,
    ...otherFields.value
  ]
  
  allFields.forEach(field => {
    if (field.default && !defaultFields.includes(field.value)) {
      defaultFields.push(field.value)
    }
  })
  
  selectedFields.value = defaultFields
  fieldOrder.value = defaultFields
}

// 保存设置 - 使用nextTick确保DOM更新完成
const handleSave = async () => {
  const fields = fieldOrder.value.filter(fieldValue => selectedFields.value.includes(fieldValue))
  emit('update:modelValue', fields)
  emit('change', fields)
  await nextTick()
  showDialog.value = false
}

// 关闭对话框
const handleClose = () => {
  selectedFields.value = [...props.modelValue]
  fieldOrder.value = [...props.modelValue]
  showDialog.value = false
}

// 监听props变化
watch(() => props.modelValue, (newValue) => {
  selectedFields.value = [...newValue]
  fieldOrder.value = [...newValue]
}, { deep: true })
</script>

<style scoped>
.field-selector {
  display: inline-block;
}

.field-settings {
  display: flex;
  gap: 20px;
  max-height: 500px;
}

.field-selection {
  flex: 1;
  max-height: 500px;
  overflow-y: auto;
  border-right: 1px solid #e4e7ed;
  padding-right: 20px;
}

.field-sorting {
  flex: 1;
  max-height: 500px;
  overflow-y: auto;
}

.field-group {
  margin-bottom: 20px;
}

.field-group h4,
.field-group h5 {
  margin: 0 0 12px 0;
  color: #606266;
  font-size: 14px;
  font-weight: 600;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 8px;
}

.field-group h5 {
  font-size: 13px;
  color: #909399;
}

.field-group .el-checkbox {
  display: block;
  margin: 8px 0;
  margin-left: 0;
}

.field-group .el-checkbox .el-tag {
  margin-left: 8px;
}

.sort-list {
  max-height: 400px;
  overflow-y: auto;
}

.sort-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  margin-bottom: 8px;
  background: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  transition: all 0.2s;
}

.sort-item:hover {
  background: #f0f2f5;
  border-color: #c0c4cc;
}

.field-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.drag-icon {
  color: #909399;
  font-size: 14px;
  font-weight: bold;
  cursor: default;
}

.field-info .el-tag {
  margin-left: 8px;
}

.sort-controls {
  display: flex;
  gap: 4px;
}

.sort-controls .el-button {
  width: 28px;
  height: 28px;
  padding: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 滚动条样式 */
.field-selection::-webkit-scrollbar,
.field-sorting::-webkit-scrollbar,
.sort-list::-webkit-scrollbar {
  width: 6px;
}

.field-selection::-webkit-scrollbar-track,
.field-sorting::-webkit-scrollbar-track,
.sort-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.field-selection::-webkit-scrollbar-thumb,
.field-sorting::-webkit-scrollbar-thumb,
.sort-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.field-selection::-webkit-scrollbar-thumb:hover,
.field-sorting::-webkit-scrollbar-thumb:hover,
.sort-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>

